import  sys
import  os
def the_file(path):
    #输入文件名 读取文件函数 返回文件的字符串#
    with open(path, 'r', encoding='utf-8') as file:
     return file.read()

def number_of_characters(word):
    #获取字符串#
    return len(word)

def number_of_words(word):
    #计算总共有几个单词#
    word = word + " "
    is_last_blank = 1
    word_count = 0
    for i in word:
        if not ((i >= "a" and i <= "z") or (i >= "A" and i <= "Z")) and is_last_blank == 0:
            is_last_blank = 1
            word_count += 1
        elif ((i >= "a" and i <= "z") or (i >= "A" and i <= "Z")) and is_last_blank == 1:
            is_last_blank = 0
    return word_count

def number_extra(str):
    flag_blank = 1
    flag_code = 1
    flag_note = 0
    last_i = " "
    all = [0, 0, 0]
    str = str + "\n"
    for i in str:
        if (i != "\n"):  # 当检测的为行内元素
            if (i != " "):  # 有非空则不可能为空行
                flag_blank = 0
        if (i == "/" or i == "#" or i == "%"):
            flag_note = 1
        if ((i == "/" or i == "#" or i == "%") and last_i == "\n"):
            flag_blank = 0
            flag_code = 0
            flag_note = 1
        if (i == "\n" and flag_blank == 1):
            flag_code = 0
            flag_note = 0
        last_i = i
        if (i == "\n"):
            all[0] += flag_blank
            all[1] += flag_code
            all[2] += flag_note
            flag_blank = 1
            flag_code = 1
            flag_note = 0
    return all

def main():
    if len(sys.argv) != 3:
        print("用法：wc.exe -c/-w <文件名>")
        print("示例：wc.exe -c file.txt （统计file.txt的字符数）")
        print("      wc.exe -w file.txt （统计file.txt的单词数）")
        print("      wc.exe -code file.txt （统计file.txt的代码行数）")
        print("      wc.exe -blank file.txt （统计file.txt的空行数）")
        print("      wc.exe -comment file.txt （统计file.txt的注释行数）")
        return

    option = sys.argv[1]  # 第二个参数：-c 或 -w
    file_path = sys.argv[2]  # 第三个参数：文件路径

    # 检查文件是否存在
    if not os.path.exists(file_path):
        print(f"错误：文件 '{file_path}' 不存在！")
        return
    word=the_file(file_path)
    # 根据选项执行统计
    extra=number_extra(word)
    if option == '-c':
        x=number_of_characters(word)
        print(x)  # 输出格式：数字 文件名（与wc一致）
    elif option == '-w':
        y=number_of_words(word)
        print(y)
    elif option == '-blank':
        m=extra[0]
        print(m)
    elif option == '-code':
        m = extra[1]
        print(m)
    elif option == '-comment':
        m = extra[2]
        print(m)
    else:
        print("错误：选项必须是 -c（字符数）或 -w（单词数）-blank(空行数) -code(代码行数) -comment（注释行数）")


if __name__ == "__main__":
 main()
#Thanks 4 ur using!


